package com.nononsenseapps.feeder.db.entity

import androidx.room.*
import com.nononsenseapps.feeder.db.FEED_ITEM
import com.nononsenseapps.feeder.db.FEED_ITEM_PRELOAD_ITEM
import com.nononsenseapps.feeder.db.room.ID_UNSET
import org.joda.time.DateTime
import org.joda.time.DateTimeZone

const val PROCESS_STATE_ERROR=-99
const val PROCESS_STATE_DEL=-1
const val PROCESS_STATE_NO_SET=0
const val PROCESS_STATE_INIT=1
const val PROCESS_STATE_PENDING=2
const val PROCESS_STATE_PROCESSING=3
const val PROCESS_STATE_PROCESSED=4
const val PROCESS_STATE_PAUSE=5

const val FEED_ITEM_PRELOAD_ITEM_TYPE_UNKNOWN="unknown"

@Entity(tableName = FEED_ITEM_PRELOAD_ITEM.tableName,
    indices = [Index(value = [FEED_ITEM_PRELOAD_ITEM.COL_FEED_ITEM_ID])],
    foreignKeys = [ForeignKey(entity = FeedItem::class,
        parentColumns = [FEED_ITEM.COL_ID],
        childColumns = [FEED_ITEM_PRELOAD_ITEM.COL_FEED_ITEM_ID],
        onDelete = ForeignKey.CASCADE)])
data class FeedItemPreLoadItem @Ignore constructor(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_ID) var id: Long = ID_UNSET,
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_FEED_ITEM_ID, defaultValue = ID_UNSET.toString()) var itemId: Long = ID_UNSET,
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_LOAD_STATE) var state: Int = PROCESS_STATE_INIT,
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_RRELOAD_URL) var preLoadUrl: String = "",
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_LOCAL_URI) var localUri: String = "",
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_IS_ENCLOSURE, defaultValue = "0") var isEnclosure: Boolean = false,
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_TYPE) var type: String = FEED_ITEM_PRELOAD_ITEM_TYPE_UNKNOWN,
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_CREATE_DATE, typeAffinity = ColumnInfo.INTEGER) var createDate: DateTime = DateTime.now(DateTimeZone.UTC),
    @ColumnInfo(name = FEED_ITEM_PRELOAD_ITEM.COL_SIZE) var size: Long = 0
){
    constructor() : this(id = ID_UNSET)

}

object PreLoadStateHelper{
    //action able check
    fun isStartAble(state: Int):Boolean = isInit(state)

    fun isPauseAble(state: Int):Boolean = isRunning(state) || isPending(state)

    fun isCancelAble(state: Int):Boolean = isPaused(state) || isRunning(state) || isPending(state)

    fun isResumeAble(state: Int):Boolean = isPaused(state) || isError(state)

    fun isDelAble(state: Int):Boolean =  isError(state) || isCompleted(state)

    //run check
    fun isPaused(state: Int):Boolean = state == PROCESS_STATE_PAUSE

    fun isRunning(state: Int):Boolean = state == PROCESS_STATE_PROCESSING

    fun isPending(state: Int):Boolean = state == PROCESS_STATE_PENDING

    fun isCompleted(state: Int):Boolean = state == PROCESS_STATE_PROCESSED

    fun isError(state: Int):Boolean = state == PROCESS_STATE_ERROR

    fun isInit(state: Int):Boolean = state == PROCESS_STATE_INIT || state == PROCESS_STATE_NO_SET
}
